package org.common.utils.consumer;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 创建一个唯实体的，重复id实体，则不会多次添加，消费者组
 * @author zhouzhibing
 * @date 2025/8/5
 */
public class ConsumerMapGroup {

    /**
     * 队列列表
     */
    private List<ConsumerMapQueue> queueList;

    private boolean start;

    /**
     * 消费对象组
     * @param config 配置
     */
    ConsumerMapGroup(ConsumerConfig config) {
        Objects.requireNonNull(config);
        Objects.requireNonNull(config.getExecutor());
        Objects.requireNonNull(config.getHandler());

        int count = config.getCount();
        queueList = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            ConsumerMapQueue consumerMapQueue = new ConsumerMapQueue(config , i);
            consumerMapQueue.start();
            queueList.add(consumerMapQueue);
        }
        start = true;
    }

    /**
     * 添加
     * @param key 唯一key
     * @param entity 实体
     */
    public void add(Long key , Object entity) {
        if(!start) {
            throw new ConsumerException("ConsumerGroup.add is close , entity = " + entity);
        }

        int index = Math.abs(Objects.hash(key) % queueList.size());
        ConsumerMapQueue consumerMapQueue = queueList.get(index);
        consumerMapQueue.add(key , entity);
    }

    /**
     * 关闭
     */
    public void close() {
        start = false;
        for (ConsumerMapQueue consumerMapQueue : queueList) {
            consumerMapQueue.close();
        }
        queueList.clear();
    }

}
